package com.qianfeng.openapi.web.master.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.openapi.web.master.mapper.ApiMappingMapper;

import com.qianfeng.openapi.web.master.pojo.ApiMapping;
import com.qianfeng.openapi.web.master.service.ApiMappingService;

import com.qianfeng.openapi.web.master.service.redisApi.CacheService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ApiMappingServiceImpl implements ApiMappingService {
    @Autowired
    private ApiMappingMapper apiMappingMapper;

    @Autowired
    private CacheService cacheService;

    private String METHOD_REDIS_PRE = "Name:";

    @Override
    public void addApiMapping(ApiMapping mapping) throws Exception {
        apiMappingMapper.addApiMapping(mapping);
        cacheService.hSet(METHOD_REDIS_PRE+mapping.getGatewayApiName() , mapping.getServiceId(), mapping.getInsideApiUrl());
    }

    @Override
    public void updateApiMapping(ApiMapping mapping) throws Exception {
        apiMappingMapper.updateApiMapping(mapping);
        cacheService.hMSet(METHOD_REDIS_PRE + mapping.getGatewayApiName(), mapping);


    }

    @Override
    public PageInfo<ApiMapping> getMappingList(ApiMapping criteria, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        return new PageInfo<>(apiMappingMapper.getMappingList(criteria));
    }

    @Override
    public ApiMapping getMappingById(int id) {
        return apiMappingMapper.getMappingById(id);
    }

    @Override
    public void deleteMapping(int[] ids) {
        if (ids == null || ids.length == 0) {
            return;
        }
        for (int id : ids) {
            ApiMapping mapping = apiMappingMapper.getMappingById(id);
            if (mapping != null) {
                mapping.setState(0);
                apiMappingMapper.updateApiMapping(mapping);
                try {
                    //从缓存中删除数据
                    cacheService.deleteKey(METHOD_REDIS_PRE + mapping.getGatewayApiName());
                    //sendMessage(SystemParams.METHOD_REDIS_PRE + mapping.getGatewayApiName(), APIRoutingType.DELETE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
